package com.issue.system.controller;

import com.issue.common.config.RuoYiConfig;
import com.issue.common.constant.Constants;
import com.issue.common.core.controller.BaseController;
import com.issue.common.core.domain.AjaxResult;
import com.issue.common.core.domain.entity.SysDictData;
import com.issue.common.core.domain.entity.SysRole;
import com.issue.common.core.domain.entity.SysUser;
import com.issue.common.core.domain.model.LoginBody;
import com.issue.common.utils.SecurityUtils;
import com.issue.common.utils.file.FileUploadUtils;
import com.issue.common.utils.file.FileUtils;
import com.issue.framework.config.ServerConfig;
import com.issue.system.domain.AChildInfo;
import com.issue.system.domain.ChildStatus;
import com.issue.system.mapper.AChildInfoMapper;
import com.issue.system.mapper.SysDictDataMapper;
import com.issue.system.mapper.SysUserMapper;
import com.issue.system.mapper.SysUserRoleMapper;
import com.issue.system.service.ISysRoleService;
import com.issue.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/app")
public class AppController extends BaseController {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysUserService userService;

    @Resource
    private ServerConfig serverConfig;

    @Resource
    private AChildInfoMapper childInfoMapper;

    @Resource
    private SysDictDataMapper sysDictDataMapper;

    @GetMapping("/loginInner")
    public AjaxResult login(@RequestParam("name") String name, @RequestParam("password") String password) {
        SysUser sysUser = sysUserMapper.selectUserByUserName(name);
        if (sysUser == null) {
            return AjaxResult.error("Account or password error");
        }
        if (!SecurityUtils.matchesPassword(password, sysUser.getPassword())) {
            return AjaxResult.error("Account or password error");
        }

        if (CollectionUtils.isEmpty(sysUser.getRoles())) {
            return AjaxResult.error("Please Contact Administrator");
        }

        String role = null;

        for (SysRole sysRole : sysUser.getRoles()) {
            if (sysRole.isAdmin()) {
                role = "admin";
                break;
            }
            if (sysRole.getRoleId() == 2) {
                role = "teacher";
            }
            if (sysRole.getRoleId() == 3 && !"teacher".equals(role)) {
                role = "guardian";
            }
        }

        Map<String, Object> params = new HashMap<>();
        params.put("userId", sysUser.getUserId());
        params.put("userName", sysUser.getUserName());
        params.put("userPassword", password);
        params.put("userPhone", sysUser.getPhonenumber());
        params.put("role", role);

        return AjaxResult.success("Login success", params);
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/insertChildStatus")
    public AjaxResult add(@RequestBody ChildStatus childStatus) {
        return AjaxResult.success();
    }

    @GetMapping("/getChildList")
    public AjaxResult getChildList(@RequestParam("teacherPhone") String teacherPhone) {
        AChildInfo childInfo = new AChildInfo();
        childInfo.setTeacherPhone(teacherPhone);
        return AjaxResult.success(childInfoMapper.selectAChildInfoList(childInfo));
    }

    @GetMapping("/getStatusList")
    public AjaxResult getStatusList() {
        List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataByType("child_status");
        return AjaxResult.success(sysDictDataList);
    }

}
